<?php

/**
 * 代理续费
 *
 * @author Alen
 * @since 1.0.0 2013-12-17
 */
class UC_RenewalAction extends PyramidUCAction {
    //put your code here
    public function index(){
        if(!$this->USER['TradePassword']) redirect('未设置交易密码','?m=UC_TradePassword_Edit');
        $bizacc=new SoBizFinanceAccount();
        $acc=$bizacc->read_one($this->USER_NAME);
        if(!$acc['State']) redirect('账户已被锁定','?m=UC_AccountLog');
        
        $this->assign('check_pwd', isset($_SESSION['tradepwd']));
        $this->assign('til', $this->USER['RenewalExpiresTime']?'续费':'开通');
        $this->assign('blance', $acc['Blance']);
        $tip='';
        if($this->USER['RenewalExpiresTime']){
                if($this->USER['RenewalExpiresTime']>date('Y-m-d H:i:s')){
                        $tip= '<label>您会员服务到期时间：'.$this->USER['RenewalExpiresTime'].' (到期后三个月内未续费将被系统注销账户，请您即时缴费)</label>';
                }else{
                        $tip= '<label>您会员服务已过期：'.$this->USER['RenewalExpiresTime'].' (到期后三个月内未续费将被系统注销账户，请您即时缴费)</label>';
                }
        }else{
                $tip= '<label>欢迎开通会员服务,请选择您要开通的年限</label>'.($acc['Blance']<300?'. <span style="color:#F00;">您的余额'.$acc['Blance'].'元，请即时充值.<a href="?m=UC_Recharge" target="_blank">[充值]</a></span>':'');
        }
        $this->assign('tip',$tip);
        $this->display();
    }
    public function checkpwd(){
        if(!request_string('Password')) redirect('密码未填写','?m=UC_Renewal&r=fail');	
        if(request_string('Password') != $this->USER['TradePassword']) redirect('密码错误','?m=UC_Renewal&r=fail');
        $_SESSION['tradepwd']='true';
        redirect('密码正确!','?m=UC_Renewal');        
    }
    
    public function save(){        
	$years=  request_numeric('Years');
	if(!$years) redirect('未选择年限');
	$amount=$years * 300;
        $bizacc=new SoBizFinanceAccount();
        $acc=$bizacc->read_one($this->USER_NAME);
        
	$acc['Blance']=$acc['Blance']-$amount;
	if($acc['Blance'] < 0) redirect('余额不足');	
        // 从账户可用余额中扣款
        $bizacc->add_transaction($this->USER_NAME,$amount,'OUT_RENEWAL');
        // 五级代理提成 100 50 30 20 10
	$bizacc->pay_to_agent($this->USER_NAME,$years);
	
	$newtime=$this->USER['RenewalExpiresTime'] && strtotime($this->USER['RenewalExpiresTime'])>strtotime(date('Y-m-d H:i:s'))?addtime("$years years",$this->USER['RenewalExpiresTime']):addtime("$years years");
        $bizuser=new SoBizUser();
        $bizuser->update_records(sprintf("RenewalExpiresTime='%s', ActiveTime='%s', ActiveIP='%s', IsAgent=1",$newtime,date('Y-m-d H:m:s'),get_client_ip())," UserName='$this->USER_NAME'");	
	
        redirect(($this->USER['RenewalExpiresTime']?'续费':'开通').'成功','?m=UC_Renewal&r=success');
    }
}
